package com.company.anr.count;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.FileSystemException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class AnrSummaryGenerator {

    // 根目录（注意反斜杠转义）
    private static final Path ROOT_A = Paths.get("D:/AMONKEY/ANR-WORK-DETAIL");

    // 当天子目录名格式：MM-dd（补零）
    private static final DateTimeFormatter DAY_FMT = DateTimeFormatter.ofPattern("MM-dd");

    // 只处理这个后缀的文件
    private static final String ANALYSIS_SUFFIX = "_analysis.txt";

    // 结果文件名（按你的拼写）
    private static final String SUMMARY_FILE_NAME = "sumary.txt";

    public static void main(String[] args) {
        String today = LocalDate.now().format(DAY_FMT);
        Path dayDir = ROOT_A.resolve(today);

        System.out.println("[INFO] Today folder: " + dayDir);

        if (!Files.isDirectory(dayDir)) {
            System.err.println("[ERROR] 目录不存在或不是目录: " + dayDir);
            System.exit(2);
        }

        List<Path> analysisFiles = listAnalysisFiles(dayDir);
        if (analysisFiles.isEmpty()) {
            System.out.println("[INFO] 未找到任何 *_analysis.txt 文件，仍将生成空统计文件。");
        }

        List<String> hasAnrSnList = new ArrayList<>();
        for (Path file : analysisFiles) {
            String fileName = file.getFileName().toString();
            System.out.println("[INFO] Processing first line of: " + fileName);

            try (BufferedReader br = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
                String firstLine = br.readLine();
                if (firstLine == null) {
                    // 空文件，跳过
                    System.out.println("[WARN] 空文件，跳过: " + fileName);
                    continue;
                }
                // 去除UTF-8 BOM可能造成的首字符异常
                firstLine = stripBom(firstLine).trim();

                if (startsWithHasAnr(firstLine)) {
                    String sn = extractSnFromFileName(fileName);
                    if (sn != null && !sn.isEmpty()) {
                        hasAnrSnList.add(sn);
                        System.out.println("[INFO] 检出有ANR: sn=" + sn);
                    } else {
                        System.out.println("[WARN] 无法从文件名提取sn，文件名不符合约定: " + fileName);
                    }
                } else if (startsWithNoAnr(firstLine)) {
                    // “无ANR日志，试用无卡顿” → 不处理
                    System.out.println("[INFO] 无ANR，跳过: " + fileName);
                } else {
                    // 非预期内容，也不处理，只提示
                    System.out.println("[WARN] 第一行内容非预期（既不是有ANR也不是无ANR），跳过: " + fileName + " | line=" + firstLine);
                }
            } catch (FileSystemException e) {
                System.err.println("[ERROR] 文件可能被占用/无权限: " + fileName + " - " + e.getClass().getSimpleName() + ": " + e.getMessage());
            } catch (IOException e) {
                System.err.println("[ERROR] 读取失败: " + fileName + " - " + e.getClass().getSimpleName() + ": " + e.getMessage());
            }
        }

        // 排序以便输出稳定
        Collections.sort(hasAnrSnList, Comparator.naturalOrder());

        // 生成 summary
        Path summaryFile = dayDir.resolve(SUMMARY_FILE_NAME);
        String content = buildSummaryContent(hasAnrSnList);
        try {
            Files.writeString(
                    summaryFile,
                    content,
                    StandardCharsets.UTF_8,
                    StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING,
                    StandardOpenOption.WRITE
            );
            System.out.println("[INFO] 汇总已写入: " + summaryFile);
        } catch (IOException e) {
            System.err.println("[ERROR] 写入汇总失败: " + summaryFile + " - " + e.getClass().getSimpleName() + ": " + e.getMessage());
            System.exit(3);
        }

        System.out.println("===== Summary =====");
        System.out.println("有ANR的SN数量: " + hasAnrSnList.size());
        System.out.println("===================");
    }

    private static List<Path> listAnalysisFiles(Path dir) {
        List<Path> result = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            for (Path p : stream) {
                if (Files.isRegularFile(p)) {
                    String name = p.getFileName().toString();
                    if (name.endsWith(ANALYSIS_SUFFIX)) {
                        result.add(p);
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("[ERROR] 遍历目录失败: " + dir + " - " + e.getClass().getSimpleName() + ": " + e.getMessage());
        }
        // 文件名升序，保证处理顺序稳定
        result.sort((a, b) -> a.getFileName().toString().compareTo(b.getFileName().toString()));
        return result;
    }

    private static boolean startsWithHasAnr(String firstLine) {
        // 只要求以“有ANR日志”开头，后面文案允许小幅出入
        return firstLine.startsWith("有ANR日志");
    }

    private static boolean startsWithNoAnr(String firstLine) {
        // 只要求以“无ANR日志”开头
        return firstLine.startsWith("无ANR日志");
    }

    private static String extractSnFromFileName(String fileName) {
        // 期望格式：<sn>_analysis.txt
        if (!fileName.endsWith(ANALYSIS_SUFFIX)) return null;
        return fileName.substring(0, fileName.length() - ANALYSIS_SUFFIX.length());
    }

    private static String buildSummaryContent(List<String> sns) {
        String lineSep = System.lineSeparator();
        int count = sns.size();
        StringBuilder sb = new StringBuilder();
        sb.append("共有").append(count).append("个sn有ANR,").append(lineSep);
        sb.append("有ANR的sn是:");
        if (!sns.isEmpty()) {
            // 用逗号连接
            for (int i = 0; i < sns.size(); i++) {
                if (i > 0) sb.append(",");
                sb.append(sns.get(i));
            }
        }
        sb.append(lineSep);
        return sb.toString();
    }

    private static String stripBom(String s) {
        // 去除可能的UTF-8 BOM (\uFEFF)
        if (s != null && !s.isEmpty() && s.charAt(0) == '\uFEFF') {
            return s.substring(1);
        }
        return s;
    }
}
